package com.zuikaku.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class DispatchServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // /user?method=login
        String methodName = req.getParameter("method");
        if(methodName==null||methodName.equals("")){
            throw new RuntimeException("未指定method参数");
        }
        //使用反射调用：请求处理函数
        Class currentServletClazz = this.getClass();
        Method methodObj = null;
        try{
            methodObj = currentServletClazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
        }catch (NoSuchMethodException e){
            e.printStackTrace();
        }
        String respStr = null;
        try {
            respStr =(String) methodObj.invoke(this,req,resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //respStr : /WEB-INF/page/home.jsp
        //respStr : redirect:/index.jsp
        if(respStr!=null&&!respStr.equals("")){
            if(respStr.contains("redirect:")){
                //重定向
                String url = respStr.substring(respStr.indexOf(":")+1);
                resp.sendRedirect(req.getContextPath()+url);

            }else{
                //forward跳转
                RequestDispatcher requestDispatcher = req.getRequestDispatcher(respStr);
                requestDispatcher.forward(req,resp);
            }


        }
    }
}
